import { MciButton } from '@/components/base/Button';
import { useFormMode } from '@/components/base/Form/mode';
import { PropType, ref } from 'vue';
import { ConjSelector } from '../DictSelector/Conj';
import { Condition } from './Condition';
import { conditionsKey, addId } from './data';
import { EConj, EOperator, ERightType, ICondition, IConditions, ILeft, IVariable } from './type';
import { ConditionSlice } from './ConditionSlice';
import { ElTag } from 'element-plus';

export const Conditions = defineComponent({
  props: {
    modelValue: {
      type: Object as PropType<IConditions>,
      default: () => ({})
    },
    leftOptions: {
      type: Array as PropType<ILeft[]>,
      default: () => []
    },
    variableOptions: {
      type: Array as PropType<IVariable[]>,
      default: () => []
    }
  },
  emits: ['update:modelValue'],
  setup(props, { /** expose,*/ emit }) {
    const formMode = useFormMode();
    // 条件
    const conditions = ref<ICondition[]>(addId(props.modelValue?.conditions));
    // 条件连接
    const conjs = ref<EConj[]>(props.modelValue?.conjs || []);
    // 条件分割
    const splitIndexes = ref<number[]>(props.modelValue?.splitIndexes || []);
    // 变量数据
    const variableData = reactive({
      variableOptions: props.variableOptions
    });

    watch(
      () => [props.modelValue, props.leftOptions, props.variableOptions],
      () => {
        if (props.modelValue) {
          conditions.value = props.modelValue.conditions || [];
          conjs.value = props.modelValue.conjs || [];
          splitIndexes.value = props.modelValue.splitIndexes || [];
        }
        variableData.variableOptions = props.variableOptions;
      },
      { immediate: true, deep: true }
    );

    provide(conditionsKey, { variableOptions: variableData });

    watchEffect(() => {
      variableData.variableOptions = props.variableOptions;
    });

    // 新增条件
    const addCondition = () => {
      const condition: ICondition = {
        left: ''
      };
      addId(condition);
      conditions.value.push(condition);

      if (conditions.value.length > 1) {
        conjs.value.push(EConj.And);
      }
      emit('update:modelValue', { conditions: conditions.value, conjs: conjs.value, splitIndexes: splitIndexes.value });
    };

    // 删除条件
    const delCondition = (index: number) => {
      conditions.value.splice(index, 1);
      if (conjs.value && conjs.value.length) {
        conjs.value.splice(index ? index - 1 : index, 1);
      }
      emit('update:modelValue', { conditions: conditions.value, conjs: conjs.value, splitIndexes: splitIndexes.value });
    };

    return () => {
      return (
        <div class="flex flex-col bg-fill-2 py-8 px-8 condition-item-row">
          <ConditionSlice
            conjs={conjs.value}
            splitIndexes={splitIndexes.value}
            onUpdate:slices={(val: number[]) => {
              splitIndexes.value = val;
              emit('update:modelValue', { conditions: conditions.value, conjs: conjs.value, splitIndexes: splitIndexes.value });
            }}
          />
          <div class={{ 'pt-8': conjs.value.length > 0 }}>
            {conditions.value &&
              conditions.value?.map((item, index) => {
                return (
                  <div class="w-full flex flex-col " key={item.id}>
                    <div class="flex items-center">
                      <ElTag>{index + 1}</ElTag>
                      <Condition
                        class="py-4 grow"
                        conditionValue={item}
                        leftOptions={props.leftOptions}
                        onCondValueChange={(val?: string) => {
                          item.right = val;
                          if (val && Array.isArray(val)) {
                            try {
                              item.right = JSON.stringify(val);
                            } catch (error) {
                              console.error(error);
                            }
                          }
                          emit('update:modelValue', {
                            conditions: conditions.value,
                            conjs: conjs.value,
                            splitIndexes: splitIndexes.value
                          });
                        }}
                        onLeftChange={(val?: string) => {
                          item.left = val;
                          emit('update:modelValue', {
                            conditions: conditions.value,
                            conjs: conjs.value,
                            splitIndexes: splitIndexes.value
                          });
                        }}
                        onOperatorChange={(val?: EOperator) => {
                          item.operator = val;
                          emit('update:modelValue', {
                            conditions: conditions.value,
                            conjs: conjs.value,
                            splitIndexes: splitIndexes.value
                          });
                        }}
                        onRightTypeChange={(val?: ERightType) => {
                          item.rightType = val;
                          emit('update:modelValue', {
                            conditions: conditions.value,
                            conjs: conjs.value,
                            splitIndexes: splitIndexes.value
                          });
                        }}
                      />
                      {formMode?.mode === 'edit' && (
                        <MciButton
                          class="px-4"
                          icon={'mci-icon-delete'}
                          link={true}
                          plain={true}
                          size={'small'}
                          onClick={() => delCondition(index)}
                        />
                      )}
                    </div>

                    {index < conjs.value.length && (
                      <div class="px-4 py-4 ml-28px">
                        <ConjSelector
                          modelValue={conjs.value[index]}
                          onUpdate:modelValue={(val: EConj) => {
                            conjs.value[index] = val;
                          }}
                        />
                      </div>
                    )}
                  </div>
                );
              })}
          </div>
          {formMode?.mode === 'edit' && (
            <div class={{ 'mt-4': conditions.value.length > 0, 'px-4': true }}>
              <MciButton text={'添加条件'} icon={'mci-icon-add'} link={true} plain={false} onClick={addCondition} />
            </div>
          )}
        </div>
      );
    };
  }
});
